package com.xi.springboot.controller;

import com.xi.springboot.annotation.SysLog;
import com.xi.springboot.entity.Result;
import com.xi.springboot.entity.Url;
import com.xi.springboot.entity.User;
import com.xi.springboot.mapper.UrlMapper;
import com.xi.springboot.service.UrlService;
import com.xi.springboot.utils.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: xjs
 * @Date: 2022/11/21/13:48
 * @Description:
 */
@Controller
public class UrlController {
    @Autowired
    UrlService urlService;
    HashMap<String,String> tempUrl = new HashMap<>();
    @SysLog("控制层:长链接转化为短链接")
   @GetMapping ("/shortenUrl")
   @ResponseBody
    public Result getUrl(HttpServletRequest request){
     String OriginUrl =request.getParameter("OriginUrl");
      String[] urls = OriginUrl.split("\r|\n");
      HttpSession session = request.getSession();
      ArrayList<String> urlList = new ArrayList<>();
      User user = (User) session.getAttribute("user");
        Boolean  b;
        for (int i = 0; i < urls.length; i++) {
            String shortenUrl = urlService.getShortenUrl(request);
            StringBuilder sb =new StringBuilder();
            if(user!=null){
                 b= urlService.bindUrl(urls[i], shortenUrl, user.getId());
                if (request.getServerPort() == 80 || request.getServerPort() == 443){
                    //http://主机名字/前缀/shortUrlId, http://localhost/a3B48/6eIcfh
                    sb.append(String.format("%s://%s/%s/%s<br>", request.getScheme(), request.getServerName(),
                            user.getSeparate(), shortenUrl));
                }else{

                    //http://主机名字/前缀/shortUrlId, http://localhost:8080/a3B48/6eIcfh
                    sb.append(String.format("%s://%s:%s/%s/%s<br>", request.getScheme(), request.getServerName(), request.getServerPort(),
                            user.getSeparate(), shortenUrl));
                }
//                sb.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort()).append("/").append(user.getSeparate()).append("/").append(shortenUrl).append("</br>");
                shortenUrl = sb.toString();
                urlList.add(shortenUrl);
            }else {
                System.out.println("前"+shortenUrl);
                tempUrl = urlService.cashUrl(urls[i], shortenUrl);
                if (request.getServerPort() == 80 || request.getServerPort() == 443){
                    //http://主机名字/前缀/shortUrlId, http://localhost/a3B48/6eIcfh
                    sb.append(String.format("%s://%s/%s/%s<br>", request.getScheme(), request.getServerName(),
                            "guest", shortenUrl));
                }else{

                    //http://主机名字/前缀/shortUrlId, http://localhost:8080/a3B48/6eIcfh
                    sb.append(String.format("%s://%s:%s/%s/%s<br>", request.getScheme(), request.getServerName(), request.getServerPort(),
                            "guest", shortenUrl));
                }
//                sb.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort()).append("/").append("guest").append("/").append(shortenUrl);
                shortenUrl = sb.toString();
                urlList.add(shortenUrl);
            }
        }
     return new Result(urlList);
   }
   @SysLog("控制层:根据短链接请求转发")
   @GetMapping("/{separate}/{shortUrl}")
    public String restUrl(@PathVariable String separate,@PathVariable String shortUrl){
    if ("guest".equals(separate)){
        if (tempUrl!=null){
            for (Map.Entry<String, String> entry : tempUrl.entrySet()) {
                if (entry.getValue().equals(shortUrl)){
                    System.out.println();
                    return "redirect:"+entry.getKey();
                }else {
                    return "noPage";
                }
            }
            return "noPage";
        }else {
            return "noPage";
        }

    }else {
        String originUrl = urlService.getOriginUrl(separate, shortUrl);
        if (originUrl!=null){
            return "redirect:"+originUrl;
        }else {
            return "noPage";
        }

    }
   }
  @SysLog("控制层:根据用户id获取对应短链接")
   @GetMapping("/getUrls")
   @ResponseBody
    public Result getUrls(HttpServletRequest request){
      HttpSession session = request.getSession();
      User user = (User) session.getAttribute("user");
      Long userId = Long.valueOf(user.getId());
       List<Url> urls = urlService.getUrls(userId);
       return new Result(urls);
   }

}
